package com.rh.i_mes.controller.ums;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rh.i_mes.common.model.PageResult;
import com.rh.i_mes.common.model.Result;
import com.rh.i_mes.common.model.SysConst;
import com.rh.i_mes.dto.UserRoleDTO;
import com.rh.i_mes.model.UmsRole;
import com.rh.i_mes.model.UmsUser;
import com.rh.i_mes.model.UmsUserRole;
import com.rh.i_mes.service.IUmsDepaService;
import com.rh.i_mes.service.IUmsRoleService;
import com.rh.i_mes.service.IUmsUserRoleService;
import com.rh.i_mes.service.IUmsUserService;
import com.rh.i_mes.util.EasyPoiExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户表
 *
 * @author hqb
 * @date 2020-09-12 16:31:21
 */
@Slf4j
@CrossOrigin
@RestController
@Api(tags = "用户表")
@RequestMapping("/ums")
public class UmsUserController {
    @Autowired
    private IUmsUserService umsUserService;
    @Autowired
    private IUmsDepaService umsDepaService;
    @Autowired
    private IUmsRoleService umsRoleService;
    @Autowired
    private IUmsUserRoleService umsUserRoleService;
    /**
     * 列表
     */
    @ApiOperation(value = "查询列表")
    @PostMapping("/umsUser/list")
    public Result<PageResult> list(@RequestBody Map<String, Object> params) {
        String code = MapUtil.getStr(params, "depaCode");
        List<String> umsDepas = StrUtil.isNotEmpty(code)?umsDepaService.getSon(params):new ArrayList<>();
        params.put("umsDepas",umsDepas);
        Page<UmsUser> list= umsUserService.findList(params);
        return Result.succeed(PageResult.restPage(list),"查询成功");
    }

    /**
     * 查询
     */
    @ApiOperation(value = "根据用户id查询 角色")
    @PostMapping("/umsUser/sel/{id}")
    public Result findUserById(@PathVariable Long id) {
        UmsUser umsUser = umsUserService.getById(id);
        List<UmsRole> roles=umsRoleService.getRoleListByUid(umsUser.getId());
        String depaCode = umsUser.getDepaCode();
        List<String> umsDepas =umsDepaService.getAllDepaBycode(new ArrayList<>(),depaCode);
        Map<String,Object> map=new HashMap<>();
        map.put("roles",roles);
        map.put("umsDepas",umsDepas);
        return Result.succeed(map, "查询成功");
    }
    /**
     * 新增
     */
    @ApiOperation(value = "新增或修改账号密码")
    @PostMapping("/umsUser/save")
    public Result save(@RequestBody UserRoleDTO userRoleDTO) {
        UmsUser umsUser = new UmsUser();
        BeanUtil.copyProperties(userRoleDTO,umsUser);
        String depaCode = umsUser.getDepaCode();
        String depaName = umsDepaService.getDepaNameByCode(depaCode);
        umsUser.setDepaName(depaName);

        List<Long> roleIds = userRoleDTO.getRoleIds();

        String userAccount = umsUser.getUserAccount();
        String userPwd = umsUser.getUserPwd();
        UmsUser existUmsUser = umsUserService.getOne(new QueryWrapper<UmsUser>().eq("user_account", userAccount));
        if (existUmsUser != null) {
            //修改角色信息
            if (roleIds != null&&roleIds.size()>0) {
                UmsUserRole umsUserRole = new UmsUserRole();
                umsUserRole.setUserId(existUmsUser.getId());
                umsUserRoleService.remove(new QueryWrapper<UmsUserRole>().eq("user_id",existUmsUser.getId()));
                for (Long roleId : roleIds) {
                    umsUserRole.setRoleId(roleId);
                    umsUserRoleService.save(umsUserRole);
                }
            }
            //修改用户部门信息
            existUmsUser.setDepaCode(depaCode);
            existUmsUser.setDepaName(depaName);
            //修改用户信息
            existUmsUser.setUserName(umsUser.getUserName());
            existUmsUser.setIsExter(umsUser.getIsExter());
            if (userPwd!=null&&StrUtil.isNotEmpty(userPwd)){
                existUmsUser.setUserPwd(SecureUtil.md5(userPwd));
            }
            umsUserService.updateById(existUmsUser);
            return Result.succeed("修改成功");
        }else {
            umsUser.setUserPwd(SecureUtil.md5(userPwd==null? SysConst.DEFAULT_PWD:userPwd));
            umsUserService.save(umsUser);
            //保存角色信息
            if (roleIds != null&&roleIds.size()>0) {
                UmsUserRole umsUserRole = new UmsUserRole();
                umsUserRole.setUserId(umsUser.getId());
                for (Long roleId : roleIds) {
                    umsUserRole.setRoleId(roleId);
                    umsUserRoleService.save(umsUserRole);
                }
            }
            return Result.succeed("保存成功");
        }
    }

    @ApiOperation(value = "登录")
    @PostMapping("/umsUser/login")
    public Result login(@RequestBody UmsUser umsUser) {
        //密码加密
        umsUser.setUserPwd(SecureUtil.md5(umsUser.getUserPwd()));
        return umsUserService.login(umsUser);
    }

    @ApiOperation(value = "用户退出")
    @PostMapping("/umsUser/logout")
    public Result logout(@RequestBody UmsUser umsUser){
        return umsUserService.logout(umsUser);
    }
    /**
     * 删除
     */
    @ApiOperation(value = "删除")
    @PostMapping("/umsUser/del")
    public Result delete(@RequestBody Map<String,List<Long>> map) {
        List<Long> ids = map.get("ids");
        umsUserService.removeByIds(ids);
        return Result.succeed("删除成功");
    }
    
    /**
     * 导入
     */
    @ApiOperation(value = "导入")
    @PostMapping("/umsUser/leadIn")
    public  Result leadIn(MultipartFile excel, String cuId) throws Exception {
        int rowNum = 0;
        if (!excel.isEmpty()) {
            List<UmsUser> list = EasyPoiExcelUtil.importExcel(excel, 1, 1, UmsUser.class);
            rowNum = list.size();
            if (rowNum > 0) {
                //无该用户信息
                list.forEach(u -> {
                        umsUserService.save(u);
                });
                return Result.succeed("成功导入信息"+rowNum+"行数据");
            }
        }
        return Result.failed("导入失败");
    }
    
    /**
     * 导出
     */
    @ApiOperation(value = "导出")
    @PostMapping("/umsUser/leadOut")
    public void leadOut(String cuId, HttpServletResponse response) throws IOException {
        List<UmsUser> umsUsers =new ArrayList<>();
        List<UmsUser> umsUserList = umsUserService.list(new QueryWrapper<UmsUser>().eq("cu_id", cuId));
        if (umsUserList.isEmpty()) {umsUsers.add(umsUserService.getById(0)); } else {
            for (UmsUser umsUser : umsUserList) {
                umsUsers.add(umsUser);
            }
        }
        //导出操作
        EasyPoiExcelUtil.exportExcel(umsUsers, "用户表导出", "用户表导出", UmsUser.class, "umsUser.xls", response);

    }
    @ApiOperation(value = "禁用/启用")
    @PostMapping("/umsUser/update")
    public Result update(@RequestBody UmsUser umsUser) {
        String userAccount = umsUser.getUserAccount();
        UmsUser user = umsUserService.getOne(new LambdaQueryWrapper<UmsUser>().eq(UmsUser::getUserAccount, userAccount));
        if (user == null) {
            return Result.failed("无此用户");
        }
        if (StrUtil.isNotBlank(umsUser.getUserPwd())){
            user.setUserPwd(SecureUtil.md5(umsUser.getUserPwd()));
        }
        umsUserService.updateById(user);
        return Result.succeed("禁用");
    }
}
